package model

import (
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	cfg "my_gin_open/build"
	rt "my_gin_open/runtime"
	"my_go_open/utils"
)

const (
	AppName = cfg.AppName
	AppKey  = cfg.AppKey
)

var (
	RpRate    *redis.Pool
	RedisPool *redis.Pool
	Mysql     *utils.Mysql
)

func init() {
	var err error
	var mysqlDsn *utils.MysqlConnOption
	logWhich := "model_init"
	if RedisPool, err = utils.RedisPool(cfg.RedisDSN); err != nil {
		rt.SaveRTLog(logWhich, cfg.RedisDSN, err)
	}
	if RpRate, err = utils.RedisPool(cfg.RedisRateDSN); err != nil {
		rt.SaveRTLog(logWhich, cfg.RedisRateDSN, err)
	}
	if mysqlDsn, err = utils.NewMysqlConnOption(cfg.MysqlDSN, 0, 0, 0, 0); err != nil {
		rt.SaveRTLog(logWhich, cfg.MysqlDSN, err)
	} else {
		Mysql = utils.NewMysql(&utils.MysqlConnParam{Master: mysqlDsn})
		Mysql.SetListener(func(err error, query string, param ...interface{}) {
			if gin.Mode() == gin.ReleaseMode && err == nil {
				return
			}
			what := make([]interface{}, 0)
			what = append(what, err)
			what = append(what, query)
			what = append(what, param...)
			rt.SaveRTLog("mysql", what...)
		})
	}
}
